package com.glory.good_dark.activity;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.good_dark.R;
import com.glory.good_dark.application.App;
import com.glory.good_dark.entity.CheckAddListEntity;
import com.glory.good_dark.entity.CheckConfirmTableName;
import com.glory.good_dark.entity.CheckState;
import com.glory.good_dark.entity.CheckTable;
import com.glory.good_dark.entity.CheckName;
import com.glory.good_dark.entity.response.BaseEntity;
import com.glory.good_dark.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: AddCheckActivity
 * Author: XJH
 * Date: 2020/4/2 18:01
 * Description: 添加检查单
 * History:
 */
public class AddCheckActivity extends BaseProjectActivity {
    @BindView(R.id.tvEqpID)
    TextView tvEqpID;
    @BindView(R.id.tvGuid)
    TextView tvGuid;
    @BindView(R.id.tvState)
    TextView tvState;
    @BindView(R.id.tvShowMan)
    TextView tvShowMan;
    @BindView(R.id.tvStartTime)
    TextView tvStartTime;
    @BindView(R.id.ivStartTimeListArrow)
    ImageView ivStartTimeListArrow;
    @BindView(R.id.flStartTimeList)
    FrameLayout flStartTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeListArrow)
    ImageView ivEndTimeListArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.BtnCancel)
    Button BtnCancel;
    @BindView(R.id.btnSave)
    Button btnSave;
    @BindView(R.id.tvFinishTime)
    TextView tvFinishTime;
    @BindView(R.id.ivFinishTimeListArrow)
    ImageView ivFinishTimeListArrow;
    @BindView(R.id.flFinishTimeList)
    FrameLayout flFinishTimeList;
    @BindView(R.id.etLongTime)
    EditText etLongTime;
    @BindView(R.id.etRemindTime)
    EditText etRemindTime;
    @BindView(R.id.tvPMType)
    TextView tvPMType;
    @BindView(R.id.etDesc)
    EditText etDesc;
    @BindView(R.id.tvPMStartTime)
    TextView tvPMStartTime;
    @BindView(R.id.ivPMStartTimeListArrow)
    ImageView ivPMStartTimeListArrow;
    @BindView(R.id.flPMStartTimeList)
    FrameLayout flPMStartTimeList;
    @BindView(R.id.tvCheckList)
    TextView tvCheckList;
    @BindView(R.id.ivCheckListArrow)
    ImageView ivCheckListArrow;
    @BindView(R.id.flCheckList)
    FrameLayout flCheckList;
    @BindView(R.id.tvRemindName)
    TextView tvRemindName;
    @BindView(R.id.ivRemindNameListArrow)
    ImageView ivRemindNameListArrow;
    @BindView(R.id.flRemindNameList)
    FrameLayout flRemindNameList;
    @BindView(R.id.tvConfirmTable)
    TextView tvConfirmTable;
    @BindView(R.id.ivConfirmTableListArrow)
    ImageView ivConfirmTableListArrow;
    @BindView(R.id.flConfirmTableList)
    FrameLayout flConfirmTableList;
    private CustomDatePicker mDatePicker;
    private String timeType = "";
    private String beginTime = "";
    private String endTime = "";
    private List<String> checkStateList;//检查单状态
    private List<String> checkNameList;//检查单名称
    private List<String> checkNameConfirmList;//工艺确认表
    private List<String> remindAlarmList;//提前提醒设置名称
    private FreeUI_GeneralPop checkNamePop;
    private FreeUI_GeneralPop checkNameConfirmPop;
    private FreeUI_GeneralPop remindAlarmPop;
    private String type;
    private String name;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_check_add;
    }

    @Override
    protected void initView() {
        tvEqpID.setText(App.EQPID);
        name = getIntent().getExtras().getString("name");
        type = getIntent().getExtras().getString("type");
        initDatePicker();
        beginTime = FreeApi_DateUtils.getNowStringDate("yyyy-MM-dd HH:mm");
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR_OF_DAY, 3);
        endTime = FreeApi_DateUtils.getStringDate(instance.getTime(), "yyyy-MM-dd HH:mm");
        tvStartTime.setText(beginTime);
        tvEndTime.setText(endTime);
        tvPMType.setText(type);

        checkNameConfirmList = new ArrayList<>();
        checkNameList = new ArrayList<>();
        checkStateList = new ArrayList<>();
        remindAlarmList = new ArrayList<>();
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            switch (timeType) {
                case "begin":
                    beginTime = FreeApi_DateUtils.long2Str(timestamp, true);
                    tvStartTime.setText(beginTime);
                    break;
                case "end":
                    endTime = FreeApi_DateUtils.long2Str(timestamp, true);
                    tvEndTime.setText(endTime);
                    break;
                case "finish":
                    tvFinishTime.setText(FreeApi_DateUtils.long2Str(timestamp, true));
                    break;
                case "PMBegin":
                    tvPMStartTime.setText(FreeApi_DateUtils.long2Str(timestamp, true));
                    break;
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(true);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    @Override
    protected void initData() {
//        String ss ="{\n" +
//                "    \"data\":{\n" +
//                "        \"BODY\":{\n" +
//                "            \"EQP_ID\":\"WB-999\",\n" +
//                "            \"CHECK_STATE_LIST\":[\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"计划中\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"待执行\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"执行中\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"待确定\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"确定中\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"CHECK_STATE_NAME\":\"执行结束\"\n" +
//                "                }\n" +
//                "            ],\n" +
//                "            \"CHECK_NAME_LIST\":[\n" +
//                "\n" +
//                "            ],\n" +
//                "            \"CHECK_NAME_CONFIRM_LIST\":[\n" +
//                "\n" +
//                "            ],\n" +
//                "            \"REMIND_ALARM_LIST\":[\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"wafer大于50\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"2wafer大于5000\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"SOS\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"日检通知\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"月检通知\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"周检通知\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"双周检通知\"\n" +
//                "                },\n" +
//                "                {\n" +
//                "                    \"REMIND_ALARM_NAME\":\"季度检通知\"\n" +
//                "                }\n" +
//                "            ],\n" +
//                "            \"CHECK_TABLE_LIST\":[\n" +
//                "\n" +
//                "            ]\n" +
//                "        },\n" +
//                "        \"HEADER\":{\n" +
//                "            \"MACHINENAME\":\"HUAWEI MLA-AL10\",\n" +
//                "            \"MESSAGENAME\":\"PDAAddCheckInfo\",\n" +
//                "            \"TRANSACTIONID\":\"515622ad-5827-42d7-8324-5b9a2727d908\",\n" +
//                "            \"EVENTTIME\":\"2020-04-23 12:04:46\"\n" +
//                "        },\n" +
//                "        \"RETURN\":{\n" +
//                "            \"RETURNCODE\":0,\n" +
//                "            \"RETURNMESSAGE\":\"请求成功！\"\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
//        BaseEntity<CheckAddListEntity> bean = (new Gson()).fromJson(ss, new TypeToken<BaseEntity<CheckAddListEntity>>() {}.getType());
//        CheckAddListEntity checkAddListEntity = bean.getData().getBody();
//        tvGuid.setText(checkAddListEntity.getCHECK_TABLE_LIST().get(0).getCHECK_ID());
//        tvState.setText(checkAddListEntity.getCHECK_TABLE_LIST().get(0).getCHECK_STATE());
//        tvShowMan.setText(checkAddListEntity.getCHECK_TABLE_LIST().get(0).getOPERATOR());
//        for (CheckState state : checkAddListEntity.getCHECK_STATE_LIST()) {
//            checkStateList.add(state.getCHECK_STATE_NAME());
//        }
//
//        for (CheckName name : checkAddListEntity.getCHECK_NAME_LIST()) {
//            checkNameList.add(name.getCHECK_NAME());
//        }
//
//        for (CheckConfirmTableName tableName : checkAddListEntity.getCHECK_NAME_CONFIRM_LIST()) {
//            checkNameConfirmList.add(tableName.getCHECK_NAME_CONFIRM());
//        }
//
//        for (CheckAddListEntity.CheckRemindName remindName : checkAddListEntity.getREMIND_ALARM_LIST()) {
//            remindAlarmList.add(remindName.getREMIND_ALARM_NAME());
//        }
        FreeUI_EntityCallBack<BaseEntity<CheckAddListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<CheckAddListEntity>>
                (new TypeToken<BaseEntity<CheckAddListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<CheckAddListEntity>> response) {
                if (response.body().isSuccess(getApplicationContext(), getSupportFragmentManager())) {
                    CheckAddListEntity checkAddListEntity = response.body().getData().getBody();
                    tvGuid.setText(checkAddListEntity.getCHECK_TABLE_LIST().get(0).getCHECK_ID());
                    tvState.setText(checkAddListEntity.getCHECK_TABLE_LIST().get(0).getCHECK_STATE());
                    tvShowMan.setText(checkAddListEntity.getCHECK_TABLE_LIST().get(0).getOPERATOR());
                    for (CheckState state : checkAddListEntity.getCHECK_STATE_LIST()) {
                        checkStateList.add(state.getCHECK_STATE_NAME());
                    }

                    for (CheckName name : checkAddListEntity.getCHECK_NAME_LIST()) {
                        checkNameList.add(name.getCHECK_NAME());
                    }

                    for (CheckConfirmTableName tableName : checkAddListEntity.getCHECK_NAME_CONFIRM_LIST()) {
                        checkNameConfirmList.add(tableName.getCHECK_NAME_CONFIRM());
                    }

                    for (CheckAddListEntity.CheckRemindName remindName : checkAddListEntity.getREMIND_ALARM_LIST()) {
                        remindAlarmList.add(remindName.getREMIND_ALARM_NAME());
                    }

                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<CheckAddListEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDAAddCheckInfo");
            }
        };

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("EQP_ID",App.EQPID);
        jsonObject.addProperty("CHECK_TYPE",type);
        jsonObject.addProperty("SUB_CLASS",name);
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDAAddCheckInfo", jsonObject);
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("添加检查单");
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    @OnClick({R.id.flCheckList,R.id.flRemindNameList,R.id.flConfirmTableList,R.id.flPMStartTimeList, R.id.flFinishTimeList, R.id.flStartTimeList, R.id.flEndTimeList, R.id.btnSave, R.id.BtnCancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flCheckList:
                if (checkNameList.size() <= 0){
                    showToast("未获取到检查单名称列表",false);
                    return;
                }
                if (checkNamePop != null) {
                    if (checkNamePop.isShowing()) {
                        checkNamePop.dismiss();
                    }
                } else {

                    checkNamePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCheckList.getWidth(), checkNameList, ivCheckListArrow, (code, i) -> {
                        tvCheckList.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivCheckListArrow);
                checkNamePop.showAsDropDown(flCheckList, 0, 0);
                break;
            case R.id.flRemindNameList:
                if (remindAlarmList.size() <= 0){
                    showToast("未获取到提前提醒名称列表",false);
                    return;
                }
                if (remindAlarmPop != null) {
                    if (remindAlarmPop.isShowing()) {
                        remindAlarmPop.dismiss();
                    }
                } else {

                    remindAlarmPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flRemindNameList.getWidth(), remindAlarmList, ivRemindNameListArrow, (code, i) -> {
                        tvRemindName.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivRemindNameListArrow);
                remindAlarmPop.showAsDropDown(flRemindNameList, 0, 0);
                break;
            case R.id.flConfirmTableList:
                if (checkNameConfirmList.size() <= 0){
                    showToast("未获取到工艺确认表列表",false);
                    return;
                }
                if (checkNameConfirmPop != null) {
                    if (checkNameConfirmPop.isShowing()) {
                        checkNameConfirmPop.dismiss();
                    }
                } else {

                    checkNameConfirmPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flConfirmTableList.getWidth(), checkNameConfirmList, ivConfirmTableListArrow, (code, i) -> {
                        tvConfirmTable.setText(code);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivConfirmTableListArrow);
                checkNameConfirmPop.showAsDropDown(flConfirmTableList, 0, 0);
                break;
            case R.id.flStartTimeList:
                timeType = "begin";
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                timeType = "end";
                mDatePicker.show(FreeApi_DateUtils.stringToLong(endTime, "yyyy-MM-dd HH:mm"));
                break;
            case R.id.btnSave:
                if (tvCheckList.getText().toString().equals("")){
                    showToast("请选择检查单名称",false);
                    return;
                }
                save();
                break;
            case R.id.BtnCancel:
                finish();
                break;
            case R.id.flFinishTimeList:
                timeType = "finish";
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flPMStartTimeList:
                timeType = "PMBegin";
                mDatePicker.show(System.currentTimeMillis());
                break;
        }
    }

    private void save() {
        FreeUI_EntityCallBack<BaseEntity<JsonObject>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<JsonObject>>
                (new TypeToken<BaseEntity<JsonObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<JsonObject>> response) {
                if (response.body().isSuccess(getApplicationContext(),getSupportFragmentManager())) {
                    showConfirmDialog(AddCheckActivity.this,"提交成功");
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<JsonObject>> response) {
                super.onError(response);
                loadError(response.getException(), "PDASaveCheckInfo");
            }
        };
        List<CheckTable> tableList = new ArrayList<>();
        tableList.clear();
        CheckTable checkTable = new CheckTable(etDesc.getText().toString(),
                App.userEntity.getNAME(),
                tvCheckList.getText().toString(),
                tvGuid.getText().toString(),
                tvEqpID.getText().toString(),
                tvState.getText().toString(),
                tvFinishTime.getText().toString(),
                tvShowMan.getText().toString(),
                tvStartTime.getText().toString(),
                tvEndTime.getText().toString(),
                etLongTime.getText().toString(),
                etRemindTime.getText().toString(),
                tvRemindName.getText().toString(),
                tvPMType.getText().toString(),
                tvPMStartTime.getText().toString(),
                tvConfirmTable.getText().toString());
        tableList.add(checkTable);
        JsonObject map = new JsonObject();
        map.addProperty("EQP_ID",App.EQPID);
        map.addProperty("CHECK_TYPE",type);
        map.addProperty("SUB_CLASS",name);
        map.add("CHECK_TABLE_LIST",new JsonParser().parse(new Gson().toJson(tableList)).getAsJsonArray());
        NetUtils.requestPostNet(App.WEB_URL + "/api/PDA", this, callBack, "PDASaveCheckInfo", map);
    }

    @Override
    protected void EQPReplaceSuccess(int tag, String content) {

    }

}
